﻿using System;
using System.IO;
using UnityEngine;
using LitJson;
using Newtonsoft.Json;

public class GE : MonoBehaviour{

    /// <summary>
    /// 倒计时time秒后，回调callBack
    /// </summary>
    public static void DownTime(float time, Action<float> callBack)
    {
        float dTime = 0;
        while (dTime < time) dTime += Time.deltaTime;

        callBack(1);
    }
    /// <summary>
    /// 得到obj与target之间的距离.
    /// </summary>
	public static float Distance(Transform obj, Vector3 target)
    {
        if (!obj ) return 0;
        Vector3 pos = obj.InverseTransformPoint(target);
        return Math.Abs(pos.z);
    }

    #region 对像处理
    /// <summary>
    /// 加载文件路径 path ,创建 Prefab 对像在target位置，isParent是否成为子对像
    /// </summary>
    public static GameObject NewObj(string path, Transform target, bool isParent)
    {
        GameObject obj = (GameObject)Resources.Load(path);
        if (isParent)
            return (GameObject)Instantiate(obj, target.position, target.rotation, target);
        else
            return (GameObject)Instantiate(obj, target.position, target.rotation);
    }
    /// <summary>
    /// 创建 Prefab 对像在target位置，isParent是否成为子对像
    /// </summary>
    public static GameObject NewObj(GameObject prefab, Transform target, bool isParent)
    {
        if (isParent)
            return (GameObject)Instantiate(prefab, target.position, target.rotation, target);
        else
            return (GameObject)Instantiate(prefab, target.position, target.rotation);
    }

    /// <summary>
    /// 查找trans节点下名称goName的对像（递归查找）  
    /// </summary> 
    public static Transform FindChild(Transform trans, string goName)
    {
        Transform child = trans.Find(goName);
        if (child != null) return child;

        Transform go = null;
        for (int i = 0; i < trans.childCount; i++)
        {
            child = trans.GetChild(i);
            go = FindChild(child, goName);
            if (go != null) return go;
        }
        return null;
    }

    /// <summary>
    /// 查找trans节点下名称goName的所有对像（递归查找）  
    /// </summary> 
    public static T FindChild<T>(Transform trans, string goName) where T : UnityEngine.Object
    {
        Transform child = trans.Find(goName);
        if (child != null) return child.GetComponent<T>();

        Transform go = null;
        for (int i = 0; i < trans.childCount; i++)
        {
            child = trans.GetChild(i);
            go = FindChild(child, goName);
            if (go != null) return go.GetComponent<T>();
        }
        return default(T);
    }
    #endregion

    #region 文件处理

    /// <summary>
    /// 打开path路径的CSV文件，返回string[]
    /// </summary>
    public static string[] LoadCsv(string path)
    {
        TextAsset file = (TextAsset)Resources.Load(path);
        string[] data = file.ToString().Split('\n');
        Debug.Log(data);
        return data;
    }

    /// <summary>
    /// 保存CSV文件, path路径, GridTop列表头，data数据
    /// </summary>
    public static void SaveCsv(string path, string GridTop, string data)
    {
        path = NowPath(path);
        StreamWriter sw = File.CreateText(path);//创建一个用于写入 UTF-8 编码的文本  
        sw.WriteLine(GridTop + '\n' + data);//以行为单位写入字符串  
        sw.Close();
        sw.Dispose();//文件流释放
    }

    /// <summary>
    /// 不同平台文件路径不同, file文件名，返回路径+文件名
    /// </summary>
    public static string NowPath(string file) {
        string path = "/Resources/" + file;
#if UNITY_EDITOR
        path = Application.dataPath + path;
#elif UNITY_IPHONE
        path = Application.persistentDataPath + file;
#elif UNITY_ANDROID
        path = Application.persistentDataPath + file;
#else
//		string.Empty;
#endif
        return path;
    }

    /// <summary>
    /// 读取JSON文件，path文件路径(不需加Json扩展名), 返回JsonData
    /// </summary>
    public static JsonData LoadJson(string path, Action<JsonData> callBack)
    {
        //Debug.Log(path);
        TextAsset file = (TextAsset)Resources.Load(path);
        JsonData jsonD = JsonMapper.ToObject(file.ToString());
        callBack(jsonD);
        return jsonD;
    }

    /// <summary>
    /// 保存JSON文件, path路径(不需加Json扩展名), data数据
    /// </summary>
    public static void SaveJson(string path, JsonData data)
    {
        path = NowPath(path + ".json");
        StreamWriter sw = File.CreateText(path);//创建一个用于写入 UTF-8 编码的文本  
        string JsonStr = data.ToJson();
        JsonStr = FormatJson(JsonStr);
        sw.WriteLine(JsonStr);//以行为单位写入字符串  
        sw.Close();
        sw.Dispose();//文件流释放
    }

    /// <summary>
    /// 格式化输出Json
    /// </summary>
    static public string FormatJson(string jsonContent)
    {
        //格式化json字符串
        JsonSerializer serializer = new JsonSerializer();
        TextReader tr = new StringReader(jsonContent);
        JsonTextReader jtr = new JsonTextReader(tr);
        object obj = serializer.Deserialize(jtr);
        if (obj != null)
        {
            StringWriter textWriter = new StringWriter();
            JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
            {
                Formatting = Formatting.Indented,
                Indentation = 4,
                IndentChar = ' '
            };
            serializer.Serialize(jsonWriter, obj);
            return textWriter.ToString();
        }
        else
        {
            return jsonContent;
        }
    }
    #endregion
}
